package com.xiaowen.config.security;

import com.xiaowen.tool.JsonUtils;
import com.xiaowen.tool.dto.ErrorCode;
import com.xiaowen.tool.dto.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: yf-wenhao
 * Date: 2024/9/18
 * Time: 下午8:42
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
            responseServiceException(httpServletResponse);
    }


    private void responseServiceException(HttpServletResponse response) {

        Result<Object> objectResult = new Result<>();
        objectResult.error(ErrorCode.UNAUTHORIZED.getCode());
        String s = JsonUtils.toJson(objectResult);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(s);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


}
